package xujiwen.transport.servlet;

import xujiwen.transport.bean.User;
import xujiwen.transport.Mgr.UserMgr;
import xujiwen.transport.bean.ChargeSTD;
import xujiwen.transport.Mgr.ChargeSTDMgr;
import xujiwen.transport.bean.Station;
import xujiwen.transport.Mgr.StationMgr;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import xujiwen.transport.util.locker.Password;

/**
 * Servlet implementation class for Servlet: Login
 * 
*/
public class Login extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	@Override
	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		final HttpSession session = request.getSession();
		final HttpSession stdsession = request.getSession();
		final HttpSession stationsession = request.getSession();
		final int uid = Integer.parseInt(request.getParameter("uid"));
		final String password = request.getParameter("password");
		System.out.println("uid=" + uid + "\t" + "password=" + password);
		final UserMgr um = new UserMgr();
		final User user = um.GetDeatilUser(uid);
		if (user == null) {
			//response.sendRedirect("showErr.jsp?err=6");
			response.getWriter().println("user not found!");
			return ;
		}
		if (user.getUclass() == 0) {
			response.getWriter().println("unuseable id!");
			return ;
		}
		
		//MD5 md5 = new MD5();
		if (user.getPassword().equals(Password.MD5(password))) {
			session.setAttribute("user", user);	// session
			
			// 创建 收费标准 保存在session中
			ChargeSTDMgr cm = new ChargeSTDMgr();
			List<ChargeSTD> stds = cm.GetSTDList();
			stdsession.setAttribute("chargeStand", stds);
			
			// 将当前站点名称保存在session中
			StationMgr sm = new StationMgr();
			stationsession.setAttribute("station", sm.GetStationByRelation(uid));
			//icom.acm.util.StaticData.application.setAttribute("user", arg1);
		} else {
			response.getWriter().println("password was wrong!");
			//
			return ;
		}
		response.sendRedirect("index.html");
	}
}